package com.fingard.dsp.bank.directbank.ceb01;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.db.JDBCHelper;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.bankInterface.IStatement;
import com.fingard.dsp.bank.reqrespobj.statement.ReqQryStatement;
import com.fingard.dsp.bank.reqrespobj.statement.RetAtsStatement;
import com.fingard.dsp.bank.reqrespobj.statement.TransState;
import com.fingard.dsp.bank.reqrespobj.statement.detail.RetAtsStatementDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.io.File;
import java.sql.Connection;
import java.util.Date;
import java.util.UUID;

public class CEB01Statement extends CEB01Base implements IStatement {
    @Override
    public RetAtsStatement d_Qry_Statement(ReqQryStatement p_reqQrySttm) throws Exception {
        RetAtsStatement retAts = new RetAtsStatement(p_reqQrySttm);
        retAts.writeStart();

        String[] tmpRespHeader5001 = getStatementb2e005001(p_reqQrySttm, retAts);
        String tmpTotalNum5001 = retAts.totalNum;
        if ("".equals(tmpTotalNum5001)) {
            tmpTotalNum5001 = "0";
        }
        String[] tmpRespHeader4002 = getStatementb2e004002(p_reqQrySttm, retAts);
        String tmpTotalNum4002 = retAts.totalNum;
        if ("".equals(tmpTotalNum4002)) {
            tmpTotalNum4002 = "0";
        }
        if ("-1".equals(tmpRespHeader4002[0]) && "-1".equals(tmpRespHeader5001[0])) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo("b2e005001接口对账单获取失败,原因:" + tmpRespHeader5001[1] + ",b2e004002接口对账单获取失败,原因:" + tmpRespHeader4002[1]);
        } else {
            if (retAts.getWrittenRdCount() == 0) {
                retAts.writeRespCode("0");
                String respInfo = tmpRespHeader4002[1];
                if (StringHelper.isNullOrEmpty(respInfo)) {
                    respInfo = "交易为空";
                }
                retAts.writeRespInfo(respInfo);
            }
            retAts.isWritedTotalNum(String.valueOf(Integer.parseInt(tmpTotalNum4002) + Integer.parseInt(tmpTotalNum5001)));
        }

        retAts.writeEnd();
        return retAts;
    }

    public String[] getStatementb2e005001(ReqQryStatement p_reqQrySttm,RetAtsStatement retAts) throws Exception {
        String[] respHeader = new String[]{"", ""};
        String tmpRespCode = "";
        String tmpRespInfo = "";
        retAts.totalNum = "0";
        int totalNum = 0;

        String fileSp = "\\|";//对账文件列分隔符
        String fileEndSp = "\r\n";//对账文件行分隔符
        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_reqQrySttm.actNum, "");
            if (actItem == null) {
                respHeader[0] = "0";
                respHeader[1] = "未找到账号" + p_reqQrySttm.actNum + "的商户配置节点";
                return respHeader;
            }
            CEB01Header bankHeader = new CEB01Header();
            bankHeader.TransCode = "b2e005001";
            bankHeader.batchID = getBatchID();
            bankHeader.JnlDateTime = p_reqQrySttm.getBusDate();
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            //写入通用的头部节点
            writeCommonHeader_2(xmlWriter, bankHeader);
            int countRd = 1;
            xmlWriter.writeStartElement("TransContent");
            XElement tmpXElement = new XElement("ReqData", "");
            tmpXElement.addChild(new XElement("ClientPatchID", bankHeader.batchID + String.format("%04d", countRd)));
            tmpXElement.addChild(new XElement("merchantId", actItem.merchantId));
            tmpXElement.addChild(new XElement("checkDate", p_reqQrySttm.busDate));
            tmpXElement.addChild(new XElement("checkFileType", getBankConfig().getValueAsString("checkFileType")));
            xmlWriter.writeXElement(tmpXElement);
            xmlWriter.writeEndDocument();//写入报文完成
            String[] tmpStrRet = sendToBank_2(xmlWriter.toXmlString(), bankHeader.TransCode);//发送银行
            String fileName = "";
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                //解析银行返回
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpReturnCode = tmpBkReader.getFirstText("/Transaction/TransContent/ReturnCode");
                    String tmpReturnMsg = tmpBkReader.getFirstText("/Transaction/TransContent/ReturnMsg");
                    if (tmpReturnCode != null && "0000".equals(tmpReturnCode)) {
                        while (tmpBkReader.read("/Transaction/TransContent/BatchRespList/RespData")) {
                            tmpRespCode = "0";
                            tmpRespInfo = tmpReturnMsg;
                            fileName = tmpBkReader.getFirstText("/Transaction/TransContent/RespData/checkFileName");
                            if (StringHelper.hasAnyChar(fileName)) {
                                break;
                            } else {
                                tmpRespCode = "0";
                                tmpRespInfo = "银行返回的节点checkFileName为空";
                            }
                        }
                    } else {
                        tmpRespCode = "0";
                        tmpRespInfo = tmpReturnMsg;
                    }
                } else {
                    tmpRespCode = "-1";
                    tmpRespInfo = tmpSbMsg.toString();
                }
            } else if (tmpStrRet[0].equals(ConnState.FAIL)) {
                tmpRespCode = "0";
                tmpRespInfo = tmpStrRet[1];
            } else {
                tmpRespCode = "-1";
                tmpRespInfo = tmpStrRet[1];
            }
            String statementFileDownPath = this.getBankConfig().getValueAsString("statementFileDownPath");
            //下载支付成功文件
            String[] tmpStrRetDownLoad = sendToBankDownloadFile("", bankHeader.TransCode, fileName);
            XmlTextReader tmpBkReaderDownLoad;
            if (tmpStrRetDownLoad[0].length() == 0) {
                StringBuilder tmpSbMsgDownLoad = new StringBuilder();
                tmpBkReaderDownLoad = loadBankRespXmlReader(tmpStrRetDownLoad[1], tmpSbMsgDownLoad);
                if (tmpBkReaderDownLoad != null) {
                    String success = tmpBkReaderDownLoad.getFirstText("/transaction/success");
                    String error = tmpBkReaderDownLoad.getFirstText("/transaction/error");
                    if (!StringHelper.isNullOrEmpty(success) && StringHelper.isNullOrEmpty(error)) {
                        //处理支付结果文件
                        if (FileHelper.existFile(statementFileDownPath + File.separator + fileName)) {
                            WriteBankLogLn("对账单结果文件：" + fileName + "下载成功!");
                            //交易日期[0]    交易码[1]   借贷标志[2]    交易金额[3]      帐户余额[4]       现转[5]   柜员流水号[6]   摘要[7]    冲补帐[8]
                            // 20150409       d028        1贷/付        6600.00    1234566718729.48     1转帐    901c24114955     0000      0无关
                            // 20150409       d028        1贷/付        1620.00    1234566720349.48     1转帐    901c24114956     0000      0无关
                            // 20150409       d028        0借/收        3375.00    1234566379163.49     1转帐    901c24115052     0000      0无关
                            String sucesFileContent = FileHelper.readFileText(statementFileDownPath + File.separator + fileName, getCharset());
                            String[] fileLine = sucesFileContent.split(fileEndSp);
                            for (int i = 0; i < fileLine.length; i++) {
                                if (fileLine[i].contains(fileSp)) {
                                    totalNum++;
                                    RetAtsStatementDetail tmpRetDetail = new RetAtsStatementDetail();
                                    String[] columns = fileLine[i].split(fileSp);
                                    tmpRetDetail.amount = columns[3];//金额
                                    tmpRetDetail.memo = columns[7];//备注
                                    tmpRetDetail.transState = TransState.Success;//备注
                                    String cdFlag = columns[2];
                                    if ("0".equals(cdFlag.substring(0, 1))) {
                                        tmpRetDetail.cdFlag = "27";
                                        tmpRetDetail.billType = "1";
                                    } else {
                                        tmpRetDetail.cdFlag = "22";
                                        tmpRetDetail.billType = "2";
                                    }

                                    retAts.writeRetDetail(tmpRetDetail);
                                }
                            }
                        }
                    } else {
                        WriteBankLogLn("对账结果文件：" + fileName + "下载失败：" + error + "\r\n");
                    }
                }
            } else {
                WriteBankLogLn("对账结果文件：" + fileName + "下载失败：" + tmpStrRetDownLoad[1] + "\r\n");
            }
        } catch (Exception ex) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(ex.getMessage());
            ex.printStackTrace();
            WriteBankLogLn(ex);
        }
        retAts.totalNum = String.valueOf(totalNum);
        respHeader[0] = tmpRespCode;
        respHeader[1] = tmpRespInfo;
        return respHeader;
    }

    public String[] getStatementb2e004002(ReqQryStatement p_reqQrySttm,RetAtsStatement retAts) throws Exception {
        String[] respHeader = new String[]{"", ""};
        String tmpRespCode = "";
        String tmpRespInfo = "";
        retAts.totalNum = "0";
        int totalNum = 0;

        Connection conn= FGBiz.getLocalDbConn();

        try {
            int totalSum = 0;
            int startPatches = 1;
            boolean queryContinue = true;
            while (queryContinue) {
                CEB01Header bankHeader = new CEB01Header();
                bankHeader.TransCode = "b2e004002";
                bankHeader.batchID = this.getBatchID();
                bankHeader.JnlDateTime = new Date();
                XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                //写入通用的头部节点
                int countRd = 1;
                writeCommonHeader_2(xmlWriter, bankHeader);
                xmlWriter.writeStartElement("TransContent");
                XElement tmpXElement = new XElement("ReqData", "");
                tmpXElement.addChild(new XElement("ClientPatchID", bankHeader.batchID + String.format("%04d", countRd)));
                tmpXElement.addChild(new XElement("AcNo", p_reqQrySttm.actNum));
                xmlWriter.writeElementString("startTime", Format.Date8Format.format(p_reqQrySttm.getBusDate()));
                xmlWriter.writeElementString("endTime", Format.Date8Format.format(p_reqQrySttm.getBusDate()));
                tmpXElement.addChild(new XElement("startPatches", String.valueOf(startPatches)));
                xmlWriter.writeXElement(tmpXElement);
                xmlWriter.writeElementString("requestPatches", "99");
                xmlWriter.writeEndDocument();

                String[] tmpStrRet = sendToBank_2(xmlWriter.toXmlString(), bankHeader.TransCode);

                if (tmpStrRet[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String tmpReturnCode = tmpBkReader.getFirstText("/Transaction/TransContent/ReturnCode");
                        String respondInfo = tmpBkReader.getFirstText("/Transaction/TransContent/ReturnMsg");
                        if (tmpReturnCode != null && "0000".equals(tmpReturnCode)) {
                            tmpRespCode = "0";

                            totalSum = tmpBkReader.getFirstText("/Transaction/TransContent/BISHUU").length() == 0 ? 0 : Integer.parseInt(tmpBkReader.getFirstText("/Transaction/TransContent/BISHUU"));
                            while (tmpBkReader.read("/Transaction/TransContent/BatchRespList/RespData")) {
                                XElement tmpRetNode = tmpBkReader.readedXElement;
                                String amount = tmpRetNode.getSingleText("JIO1JE");
                                String summary = tmpRetNode.getSingleText("ZHYODM");
                                String askNumber = tmpRetNode.getSingleTextNotNull("respond2");
                                if (amount.startsWith("-") || "网银电子汇划费".equalsIgnoreCase(summary) || StringHelper.isNullOrEmpty(askNumber)) {
                                    continue;
                                }
                                totalNum++;

                                RetAtsStatementDetail tmpRetDetail = new RetAtsStatementDetail();
                                tmpRetDetail.askNumber = askNumber;
                                String busTime = tmpRetNode.getSingleText("JIOYRQ") + tmpRetNode.getSingleText("JIOYSJ");
                                tmpRetDetail.busTime = Format.DateTime14Format.format(Format.DateTime14Format.parse(busTime));//格式2016-08-01
                                tmpRetDetail.memo = tmpRetNode.getSingleTextNotNull("BEIZXX").trim();
                                if (StringHelper.isNullOrEmpty(tmpRetDetail.memo)) {
                                    tmpRetDetail.memo = tmpRetNode.getSingleTextNotNull("ZHYODM").trim();
                                }
                                tmpRetDetail.oprCode = tmpRetNode.getSingleText("GUIYLS");
                                tmpRetDetail.bkSeq = tmpRetNode.getSingleText("ClientPchID");
                                if (StringHelper.isNullOrEmpty(tmpRetDetail.bkSeq)) {
                                    tmpRetDetail.bkSeq = tmpRetNode.getSingleText("ClientBchID");
                                }
                                //借贷标记(0-借,1-贷)
                                String bkDcFlag = tmpRetNode.getSingleText("JIEDBZ");
                                if ("0".equals(bkDcFlag)) {
                                    tmpRetDetail.cdFlag = "27";  //(27：代付)
                                    tmpRetDetail.billType = "1";  //(1:借)
                                } else if ("1".equals(bkDcFlag)) {
                                    tmpRetDetail.cdFlag = "22";  //(22：代扣)
                                    tmpRetDetail.billType = "2";  //(2:贷)
                                } else {
                                    tmpRespCode = "-1";
                                    tmpRespInfo = "借贷标志有误，值：" + bkDcFlag;
                                    break;
                                }
                                tmpRetDetail.oppAct = tmpRetNode.getSingleTextNotNull("DUIFZH").trim();
                                tmpRetDetail.oppActName = tmpRetNode.getSingleTextNotNull("DUIFMC").trim();
                                tmpRetDetail.amount = tmpRetNode.getSingleText("JIO1JE");
                                tmpRetDetail.transState = TransState.Success;

                                String INSERTSEQ = "INSERT INTO REQSEQIDMAPPING(URID,BANKCODE,REQSEQID,BANKREQSEQID) values (?,?,?,?);";
                                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                                JDBCHelper.update(conn, INSERTSEQ, new Object[]{uuid, "CEB01", tmpRetDetail.askNumber, tmpRetNode.getSingleTextNotNull("GUIYLS").trim()});

                                retAts.writeRetDetail(tmpRetDetail);
                            }
                            startPatches += 99;
                            if (!(startPatches < totalSum && totalSum != 0 && (totalSum > 99))) {
                                queryContinue = false;
                            }
                        } else {
                            String returnInfo = tmpBkReader.getFirstText("/transaction/ReturnMsg");
                            //该期间确实没有交易记录
                            if (StringHelper.isNullOrEmpty(returnInfo) || !returnInfo.contains("已无符合条件的记录")) {
                                tmpRespCode = "-1";
                                respondInfo = respondInfo + " " + returnInfo;
                            }
                            tmpRespInfo = respondInfo;
                            break;
                        }
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpSbMsg.toString();
                        break;
                    }
                } else {
                    tmpRespCode = "-1";
                    tmpRespInfo = tmpStrRet[1];
                    break;
                }
            }
        } catch (Exception ex) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(ex.getMessage());
            ex.printStackTrace();
            WriteBankLogLn(ex);
        } finally {
            if (conn != null) {
                conn.close();
            }
        }
        retAts.totalNum = String.valueOf(totalNum);
        respHeader[0] = tmpRespCode;
        respHeader[1] = tmpRespInfo;
        return respHeader;
    }
}
